package wh.coach._ser;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author hangwen
 * @date 2023/7/17
 */
public class PersonSerAndDeSer {

    //作业
    //1. 处理null的情况
    //2. 二进制数据感觉还是有很多垃圾空间 思考
//    compress和decompress方法
    //bitmap

    public static Person read(byte[] data) {
        final ByteArrayInputStream is = new ByteArrayInputStream(data);
        final DataInput dataInput = new DataInputStream(is);

        Person person = new Person();

        try {
            final long id = dataInput.readLong();
            person.setId(id);

            final int age = dataInput.readInt();
            person.setAge(age);

            final int lengthOfName = dataInput.readInt();
            byte[] dataOfName = new byte[lengthOfName];
            dataInput.readFully(dataOfName);
            String name = new String(dataOfName, StandardCharsets.UTF_8);
            person.setName(name);

            return person;
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }

    }

    public static byte[] write(Person person) {
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        final DataOutput dataOutput = new DataOutputStream(os);

        try {
            dataOutput.writeLong(person.getId());
            dataOutput.writeInt(person.getAge());
            final byte[] name = person.getName().getBytes(StandardCharsets.UTF_8);
            dataOutput.writeInt(name.length);
            dataOutput.write(name);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }

        return os.toByteArray();
    }

}
